package com.syeet.gulimall.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syeet.common.utils.PageUtils;
import com.syeet.common.utils.Query;
import com.syeet.common.utils.R;
import com.syeet.common.vo.MemberRespVo;
import com.syeet.gulimall.order.constant.OrderConstant;
import com.syeet.gulimall.order.dao.OrderDao;
import com.syeet.gulimall.order.entity.OrderEntity;
import com.syeet.gulimall.order.entity.OrderItemEntity;
import com.syeet.gulimall.order.enume.OrderStatusEnum;
import com.syeet.gulimall.order.exception.NoStockException;
import com.syeet.gulimall.order.feign.CartFeignService;
import com.syeet.gulimall.order.feign.MemberFeignService;
import com.syeet.gulimall.order.feign.ProductFeignService;
import com.syeet.gulimall.order.feign.WareFeignService;
import com.syeet.gulimall.order.interceptor.LoginUserInterceptor;
import com.syeet.gulimall.order.service.OrderItemService;
import com.syeet.gulimall.order.service.OrderService;
import com.syeet.gulimall.order.to.OrderCreateTo;
import com.syeet.gulimall.order.vo.*;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSumbitVo> orderSumbitVoThreadLocal = new ThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Resource
    private ThreadPoolTaskExecutor executor;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取订单详情
     *
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //RequestContextHolder底层是利用threadlocal,异步编排下不同线程
        // 在GuliFeignConfig配置中导致feign调用丢失上下文
        //解决方法：把主线程的RequestAttributes依次复制到要调用的异步线程中
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(attributes);
            //1.远程查询所有收货地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        /**
         *
         * feign远程调用会丢失请求头，丢失了cookies信息，导致远程调用
         * cartFeignService时，gulimall-cart的拦截器中获取的用户信息为空，
         * 造成getCurrentUserCartItems（）获取值为空
         * 原因：feign在远程调用之前会构造请求，依次调用很多拦截器RequestInterceptor
         * 解决方法：若有请求头，需在拦截器添加，本列中在GuliFeignConfig添加了RequestInterceptor
         *
         * 2.远程查询购物车所有选中的购物项
         */
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(attributes);
            List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(cartItems);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.getSkuHasStock(collect);
            List<SkuHasStockVo> data = r.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if (!CollectionUtils.isEmpty(data)) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);


        //3.查询用户积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);
        //4.其他数据自动计算

        //TODO 5.防重令牌
        //使用token,保证接口幂等性，避免多次点击提交订单按钮时，提交多份订单，只生成一份订单
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);

        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);

        CompletableFuture.allOf(getAddressFuture, cartFuture).get();

        return confirmVo;
    }

    /**
     * 同一个对象内事务相互调用默认失效，原因是跳过了代理对象
     * 事务是使用代理对象控制的
     */
    @Transactional(timeout = 30) //a事务的设置都会传播到和他共用同一个事务的方法
    public void a(){
        //b c任何设置都没有，都是和a共用一个事务
      //  this.b();失效
       // this.c(); 失效
        OrderServiceImpl orderService= (OrderServiceImpl)AopContext.currentProxy();
        orderService.b();
        orderService.c();

       // bService.b(); 传播性，共用a事务
        // cService.c();开启新事物
    }
    @Transactional(propagation = Propagation.REQUIRED)
    public void b(){

    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void c(){

    }


    /**
     * 提交订单
     * <p>
     * 流程：
     * <p>
     * 2.验证令牌（使用token，保证接口幂等性，避免多次点击提交订单按钮时，提交多份订单，只生成一份订单）
     * 1.去创建订单，生成订单
     * 3.验证价格
     * 4.锁库存
     * 5.。。。
     *
     *  @GlobalTransactional使用seata解决分布式事务、、
     *  seata默认使用at模式，可以理解为2pc升级版，不适用于高并发场景
     *
     * @param vo
     * @return
     */
    //@GlobalTransactional
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderRespVo submitOrder(OrderSumbitVo vo) {
        orderSumbitVoThreadLocal.set(vo);
        SubmitOrderRespVo respVo = new SubmitOrderRespVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        respVo.setCode(0);
        //1.验证令牌(令牌的对比和删除必须保证原子性)
        String orderToken = vo.getOrderToken();
        //0验证失败，1成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        //通过lure脚本原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        if (result == 0L) {
            //验证失败
            respVo.setCode(1);
            return respVo;
        } else {
            //成功
            //2.创建所有订单信息，其包括订单表和订单项表信息
            OrderCreateTo order = createOrder();

            //3、验证价格
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();

            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比在合理范围内
                //TODO 4、保存订单
                saveOrder(order);

                //5、库存锁定,只要有异常，回滚订单数据
                //订单号、所有订单项信息(skuId,skuNum,skuName)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                //获取出要锁定的商品数据信息
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map((item) -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());

                lockVo.setLocks(orderItemVos);

                //TODO 5、调用远程锁定库存的方法
                //出现的问题：扣减库存成功了，但是由于网络原因超时，出现异常，导致订单事务回滚，库存事务不回滚(解决方案：seata)
                //为了保证高并发，不推荐使用seata，因为是加锁，并行化，提升不了效率,可以发消息给库存服务
                R r = wareFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    //锁成功
                    respVo.setOrderEntity(order.getOrder());
                    //TODO 6、远程优惠卷服务,出异常(重现远程调用失败)
                    //订单回滚，库存不回滚
                    int i = 10/0;
                    return respVo;
                } else {
                    //锁库存失败了
//                    respVo.setCode(3);
//                    return respVo;
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }

            } else {
                //验价格，不在合理范围
                respVo.setCode(2);
                return respVo;
            }
        }

//        final String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        if (orderToken != null && orderToken.equals(redisToken)){
//            //令牌验证通过，先删除令牌
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        }else {
//            //不通过
//        }

    }

    /**
     * 保存订单
     *
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        //获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(order);

        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //批量保存订单项数据
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建所有订单信息
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderSumbitVo orderSumbitVo = orderSumbitVoThreadLocal.get();
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        try {
            //1.生成订单号
            String orderSn = IdWorker.getTimeId();
            //2.完成订单表信息
            OrderEntity orderEntity = buildOrderEntities(orderSumbitVo, orderSn);

            //3.完成订单项表信息
            List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
            //4.计算价格相关
            computerPrice(orderEntity, orderItemEntities);

            orderCreateTo.setOrder(orderEntity);
            orderCreateTo.setOrderItems(orderItemEntities);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            orderSumbitVoThreadLocal.remove();
        }
        return orderCreateTo;
    }

    /**
     * 计算价格 积分相关信息
     *
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠券抵扣金额
        BigDecimal coupon = new BigDecimal("0.0");
        //积分抵扣金额
        BigDecimal intergration = new BigDecimal("0.0");
        //促销优化金额（促销价、满减、阶梯价）
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 构建订单表信息
     *
     * @param orderSumbitVo
     * @param orderSn
     */
    private OrderEntity buildOrderEntities(OrderSumbitVo orderSumbitVo, String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());
        //计算运费
        R r = wareFeignService.getFare(orderSumbitVo.getAddrId());
        FareVo fareData = r.getData(new TypeReference<FareVo>() {
        });
        //设置运费信息
        orderEntity.setFreightAmount(fareData.getFare());
        //设置收货人信息
        orderEntity.setReceiverCity(fareData.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareData.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareData.getAddress().getName());
        orderEntity.setReceiverPhone(fareData.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareData.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareData.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareData.getAddress().getRegion());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

    /**
     * 根据整个购物车项构建所有订单项表信息
     *
     * @param
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //获取所有订单项
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (CollectionUtil.isNotEmpty(currentUserCartItems)) {
            List<OrderItemEntity> orderItemEntities = currentUserCartItems.stream().map(orderItemVo -> {
                //根据单个购物车项构建单个订单项表信息
                OrderItemEntity orderItemEntity = buildOrderItem(orderItemVo);
                //订单信息 ：订单号
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());

            return orderItemEntities;
        }
        return Collections.emptyList();
    }

    /**
     * 根据单个购物车项构建单个订单项表信息
     *
     * @param items
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo items) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //订单信息 ：订单号

        //1、商品的spu信息
        Long skuId = items.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandId().toString());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount().toString())).intValue());

        //5、订单项的价格信息
//        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
//        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
//        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格(实际应去查询)
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

}